import 'dart:convert';
import 'dart:io';

import 'package:file_picker/file_picker.dart';

class LWUnitls {
  static execute(String command, Function callback) async {
    // String commands = 'ls'; // 启动进程并获取进程对象
    // Process process = await Process.start(commands, []);
    Process process = await Process.start('/bin/bash', ['-c', command]);
    // 使用流监听标准输出
    process.stdout.transform(utf8.decoder).listen((String data) {
      callback(data);
    });

    // 使用流监听标准错误
    process.stderr.transform(utf8.decoder).listen((String data) {
      callback(data);
    });

    // 等待进程执行完成
    int exitCode = await process.exitCode;
  }

  static changeCurrentPath(String targetPath) {
    // 获取当前工作目录
    String currentDirectory = Directory.current.path;
    print('Current Directory: $currentDirectory');

    // 要切换到的目录路径
    // String targetDirectory = '/path/to/your/directory';

    // 使用 try-catch 处理可能的异常
    try {
      // 创建一个 Directory 对象
      Directory newDirectory = Directory(targetPath);

      // 检查目录是否存在
      if (newDirectory.existsSync()) {
        // 使用 setCurrent 方法切换当前工作目录
        Directory.current = newDirectory;
        print('Successfully changed to $targetPath');
      } else {
        print('Directory does not exist: $targetPath');
      }
    } catch (e) {
      print('Error: $e');
    }
    // 获取切换后的当前工作目录
    String updatedDirectory = Directory.current.path;
    print('Updated Current Directory: $updatedDirectory');
  }

  /// 选择文件/文件夹
  static chooseFile(Function callback, {bool isDirectory = false}) async {
    if (isDirectory) {
      String? selectedDirectory = await FilePicker.platform.getDirectoryPath();
      if (selectedDirectory != null) {
        callback(selectedDirectory);
      }
      return;
    }
    FilePickerResult? result = await FilePicker.platform.pickFiles();
    if (result != null) {
      File file = File(result.files.single.path!);
      callback(file.path);
    }
  }
}
